package net.araim.bbingo;

import net.araim.bbingo.activity.CorporateBingo;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageButton;

public class ToggleImageButton extends ImageButton {

	public static int counter = 0;
	private boolean on = false;
	private Drawable onButton = null;
	private Drawable offButton = null;

	public boolean isOn() {
		return on;
	}

	public void setOn(boolean on) {
		this.on = on;
		setImage();
	}

	private void setImage() {
		if (on) {
			this.setImageDrawable(onButton);
		} else {
			this.setImageDrawable(offButton);
		}
		invalidate();
	}

	public boolean toggle() {
		this.on = !this.on;
		setImage();
		return this.on;
	}

	public Drawable getOnButton() {
		return onButton;
	}

	public void setOnButton(Drawable onButton) {
		this.onButton = onButton;
		invalidate();
	}

	public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context, attrs);
		counter++;
		Log.d(CorporateBingo.LOGTAG, "Object created (" + counter + ")");
	}

	public ToggleImageButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
		counter++;
		Log.d(CorporateBingo.LOGTAG, "Object created (" + counter + ")");
	}

	private void init(Context context, AttributeSet attrs) {
		TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
		int i = ta.getResourceId(R.styleable.ToggleImageButton_onButtonRes, 0); // onbutton
		if (i != 0) {
			setOnButton(i);
		}
		i = ta.getResourceId(R.styleable.ToggleImageButton_offButtonRes, 0); // onbutton
		if (i != 0) {
			setOffButton(i);
		}
		ta.recycle();
		setImage();
	}

	public void setOnButton(int onButtonRes) {
		this.onButton = getContext().getResources().getDrawable(onButtonRes);
		invalidate();
	}

	public Drawable getOffButton() {
		return offButton;
	}

	public void setOffButton(Drawable offButton) {
		this.offButton = offButton;
		invalidate();
	}

	public void setOffButton(int offButtonRes) {
		this.offButton = getContext().getResources().getDrawable(offButtonRes);
		invalidate();
	}

	public ToggleImageButton(Context context) {
		super(context);
		setImage();
		counter++;
		Log.d(CorporateBingo.LOGTAG, "Object created (" + counter + ")");
	}

}
